<template>
  <div>
    <div class="app-container">
      <TopInfo />

      <Search :lookup="data.lookup" @investigate="inves" />

      <el-button type="primary" size="small" @click="add">
        <template #default>
          <span class="text-sm">{{ $t("goods.list.add") }}</span>
        </template>
      </el-button>

      <el-button
        v-prmis="'goods_importExcel'"
        type="success"
        size="small"
        @click="setspread"
      >
        <template #default>
          <span class="text-sm">{{ $t("goods.list.import") }}</span>
        </template>
      </el-button>

      <el-button
        v-prmis="'goods_exportExcel'"
        type="warning"
        size="small"
        @click="getspread"
      >
        <template #default>
          <span class="text-sm">{{ $t("goods.list.export") }}</span>
        </template>
      </el-button>

      <el-button
        v-prmis="'goods_del'"
        type="danger"
        size="small"
        @click="delspread"
      >
        <template #default>
          <span class="text-sm">{{ $t("goods.list.del") }}</span>
        </template>
      </el-button>
    </div>

    <div class="app-container" v-loading="data.mtloading">
      <el-table
        :data="data.list"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        class="w-full"
        @selection-change="handleSelectionChange"
        height="650"
      >
        <el-table-column type="index" width="55" :label="$t('public.No')" />
        <el-table-column type="selection" width="65" />

        <el-table-column prop="pic" :label="$t('machine.goods.pic')">
          <template #default="scope">
            <img
              class="w-20 h-20 inline-block"
              :src="scope.row.pic || product"
              @click="url(scope.row.pic)"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="g_name"
          :label="$t('machine.goods.name')"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.g_name || "--" }}
          </template>
        </el-table-column>

        <el-table-column
          prop="model"
          :label="$t('machine.goods.marque')"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.model || "--" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="g_type"
          :label="$t('machine.goods.type')"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ setGtype(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="gc_name"
          :label="$t('machine.goods.class')"
          show-overflow-tooltip
        />

        <el-table-column prop="sku" label="SKU" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.sku || "--" }}
          </template>
        </el-table-column>

        <el-table-column :label="$t('machine.goods.costPrice')">
          <template #default="scope">
            {{ scope.row.cost_price || "0.00" }}
          </template>
        </el-table-column>

        <el-table-column :label="$t('machine.goods.marketValue')">
          <template #default="scope">
            {{ scope.row.market_price || "0.00" }}
          </template>
        </el-table-column>

        <el-table-column :label="$t('machine.goods.retailPrice')">
          <template #default="scope">
            {{ scope.row.retail_price || "0.00" }}
            <el-link
              type="primary"
              :underline="false"
              @click="getreal(scope.row.g_id)"
              >{{ $t("machine.goods.actualPrice") }}</el-link
            >
          </template>
        </el-table-column>

        <el-table-column :label="$t('public.operate')" width="260">
          <template #default="scope">
            <el-button
              v-prmis="'goods_lang'"
              type="success"
              size="small"
              @click="language(scope.row)"
            >
              {{ $t("public.lang") }}
            </el-button>
            <el-button type="primary" size="small" @click="modify(scope.row)">
              {{ $t("public.edit") }}
            </el-button>
            <el-button
              v-prmis="'goods_add'"
              type="warning"
              size="small"
              @click="setcopy(scope.row)"
            >
              {{ $t("public.copy") }}
            </el-button>
            <el-button
              v-prmis="'goods_del'"
              type="danger"
              size="small"
              @click="del(scope.row.g_id)"
            >
              {{ $t("public.del") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <PageNum
        :total="data.total"
        :page="data.goods"
        @exposeData="current"
        @fraction="fraction"
      />
    </div>

    <!-- 图片商品展示 -->
    <el-dialog
      v-model="data.demonstrate"
      :title="data.title"
      center
      :width="data.gmactype ? '40%' : '30%'"
    >
      <goodsprice
        v-if="data.gmactype"
        :list="data.pricelist"
        @edit="editprice"
      />
      <el-image v-else :src="data.file_path" fit="fill" />
    </el-dialog>

    <!-- 语言设置弹窗 -->
    <el-dialog
      v-if="data.dialogVisible"
      v-model="data.dialogVisible"
      :title="$t('machine.goods.setLang')"
      center
      width="60%"
      class="h-3/4 overflow-auto mt-4"
      style="margin-top: 30px; height: 90%"
    >
      <goodslang
        :formance="data.performance"
        :info="data.langobj"
        :lang="data.languagelist"
      />
    </el-dialog>

    <!-- 导入商品 -->
    <el-dialog
      v-if="data.dialoggoods"
      v-model="data.dialoggoods"
      :title="$t('goods.list.import')"
      center
      width="20%"
    >
      <goodsimport @exposeData="exposegoods" />
    </el-dialog>

    <exports :dialogVisible="dialogExport" @close="dialogExport = false" />
  </div>
</template>

<script lang="ts" setup>
import { useI18n } from "vue-i18n";
const { t: $t } = useI18n();
import TopInfo from "@/components/TopInfo/index.vue";
import Search from "@/components/Search/index.vue";
import PageNum from "@/components/PageNum/index.vue";
import goodslang from "../common/goods_lang.vue";
import goodsprice from "../common/goods_price.vue";
import goodsimport from "../common/goods_import.vue";
import product from "@/assets/product.png";
import { authority } from "@/utils/menu";
import { useRouter, useRoute } from "vue-router";
import {
  getgoodsList,
  addgoods,
  delgoods,
  updateMoreByGid,
  exportgoodsExcel,
  getListcategory,
} from "@/api/goods";
import { getperform, getlang } from "@/api/manage";
import { getmacgoodsList } from "@/api/machine";
import { ElMessage, ElMessageBox } from "element-plus";
import exports from "@/components/export.vue";
const dialogExport = ref(false);
const router = useRouter();
const route = useRoute();
enum State {
  OK = 200
}
let data:any = reactive({
  mtloading: false, // 加载
  demonstrate: false, // 商品图片弹窗
  dialogVisible: false, // 添加修改商品弹窗
  gmactype: false, // 实际售价类型
  dialoggoods: false, // 导入商品
  file_path: "", // 商品图片
  title: "", //弹窗标题
  lookup: [
    // 筛选栏
    {
      title: $t("machine.goods.name"),
      type: "input",
      value: "",
      key: "g_name",
    },
    {
      title: $t("machine.goods.class"),
      type: "linkage",
      select: [],
      value: "",
      key: "gc_id",
      strictly: true,
    },
    {
      title: $t("machine.goods.skuCode"),
      type: "input",
      value: "",
      key: "sku",
    },
    {
      title: $t("machine.goods.skuCodes"),
      type: "input",
      value: "",
      key: "sku2",
    },
    {
      title: $t("goods.list.status"),
      type: "define",
      select: [
        { label: $t("public.enable"), value: 1 },
        { label: $t("public.prohibit"), value: 2 },
      ],
      value: "",
      key: "status",
    },
    {
      title: $t("machine.goods.type"),
      type: "define",
      select: [
        { label: $t("goods.groupM.normalGood"), value: 1 },
        { label: $t("goods.groupM.hotelGood"), value: 2 },
        { label: $t("goods.groupM.ticket"), value: 3 },
      ],
      value: "",
      key: "g_type",
    },
  ],
  goods: {
    // 筛选数据
    g_name: "",
    gc_id: "",
    sku: "",
    sku2: "",
    status: "",
    page: 1,
    pageNum: 15,
  },
  total: 0, // 总条数
  list: [], // 列表信息
  goodsID: [], // 选中的商品信息
  langobj: {}, // 选中的语言商品
  performance: [], // 性能信息
  languagelist: [], // 语言列表信息
  pricelist: [], // 实际售价信息
  power: {}, // 权限
});

// 获取数据
let getlisttype = () => {
  authority({}).then((res) => {
    data.power = res;
  });

  if (route.query.l != undefined) {
    let info = route.query.l;
    data.goods.sku = info;
    for (let item of data.lookup) {
      if (item.key == "sku") {
        item.value = info;
      }
    }
  }
  getlist();
};

interface GoodsData {
  g_name: string;
  gc_id: string;
  sku: string;
  sku2: string;
  status: string;
  page?: number;
  pageNum?: number;
  [key: string]: any;
}
// 查询回调
let inves = (e: GoodsData): void => {
  data.goods.gc_id = "";
  for (let key in e) {
    if (key != "gc_id") {
      data.goods[key] = e[key];
    }
  }

  if (e.gc_id != "") {
    data.goods.gc_id = e.gc_id[e.gc_id.length - 1];
  }
  data.goods.page = 1;
  data.goods.pageNum = 15;
  getlist();
};

interface  Select<T> {
	label: string;
	value?: string | number;
  gc_pid?: string | number;
  children: T
}
// 获取商品分类
let gettype = () => {
  let select = []
  data.lookup[1].select = [];
  getListcategory({}).then((res:any) => {
    if (res.state == State.OK) {
      for (let item of res.data) {
        select.push({
          label: item.gc_id + "-" + item.gc_name,
          value: item.gc_id,
          gc_pid: item.gc_pid,
          children: []
        })
      }
      select.forEach((item:Select) => {
        select.find((ime) => {
          if (ime.gc_pid == item.value) {
            item.children.push(ime)
          }
        })
      });
      for (let item of select) {
        if (item.gc_pid == 0) {
          data.lookup[1].select.push(item);
        }
      }
    }
  });
  getlanglist();
};

// 获取商品信息
let getlist = () => {
  data.mtloading = true;
  let goods_info:any = {};
  for (let key in data.goods) {
    if (data.goods[key] != "") {
      goods_info[key] = data.goods[key];
    }
  }
  getgoodsList(goods_info)
    .then((res:any) => {
      data.goodsID = [];
      data.mtloading = false;
      if (res.state == State.OK) {
        data.list = res.data.data;
        data.total = res.data.total;
      }
    })
    .catch((err) => {
      data.mtloading = false;
    });
};

// 获取真实售价
let getreal = (e:string | number) => {
  data.title = $t("machine.channel.price");
  data.gmactype = true;
  data.demonstrate = true;
  data.pricelist = [];
  getmacgoodsList({ g_id: e }).then((res) => {
    if (res.state == State.OK) {
      data.pricelist = res.data;
    }
  });
};

// 真实数据回调信息
let editprice = (e:any) => {
  data.title = "";
  data.gmactype = false;
  data.demonstrate = false;
  data.pricelist = [];
  if (e != false) {
    updateMoreByGid(e).then((res) => {
      if (res.state == State.OK) {
        ElMessage({
          message: $t("message.modifySuccess"),
          type: "success",
        });
        return;
      }
    });
  }
};

// 选中的商品
let handleSelectionChange = (e:any[]) => {
  data.goodsID = [];
  for (let item of e) {
    data.goodsID.push(item.g_id);
  }
};
// 获取性能信息
let getformance = () => {
  if (data.performance.length != 0) {
    return;
  }
  getperform({}).then((res) => {
    if (res.state == State.OK) {
      data.performance = res.data;
    }
  });
};

// 商品多语言按钮
let language = (e:any) => {
  data.dialogVisible = true;
  data.langobj = e;
};

// 获取多语言
let getlanglist = () => {
  if (data.languagelist.length != 0) {
    return;
  }
  getformance();
  getlang({}).then((res) => {
    if (res.state == State.OK) {
      data.languagelist = res.data;
    }
  });
};

// 添加商品按钮
let add = () => {
  router.push({ path: "/goods/info/add_info" });
};

// 修改商品按钮
let modify = (e:any) => {
  let query = {
    id: e.g_id,
  };
  router.push({ path: "/goods/info/details_info", query: query });
};

// 删除商品按钮
let del = (e:string | number) => {
  ElMessageBox.confirm($t("message.delData"))
    .then((res) => {
      delgoods({ g_id: e }).then((res) => {
        if (res.state == State.OK) {
          ElMessage({
            message: $t("message.delSuccess"),
            type: "success",
          });
          data.dialogVisible = false;
          getlist();
          return;
        }
        ElMessage({
          message: $t("message.networkFailed"),
          type: "error",
        });
      });
    })
    .catch((err) => {
      console.log("取消");
    });
};

interface Setcopyobj{
	ao_id?: string | number;
    bar_code: string;
    cost_price: string;
    g_name: string;
    gc_id?: string | number;
    gc_name: string;
    model: string;
    sku: string;
    sku2: string;
    pic: string;
    market_price: string;
    retail_price: string;
    manufacturer: string;
    service_phone: string;
    desc: string;
    heat: number;
    is_gift: number;
    is_recommend: number;
    recoverable: number;
    performance: string;
    sell_channel: number;
    expire_notice: number;
    length: string;
    width: string;
    height: string;
    group_quantity: string;
    release_time: string;
    status: number;
	[key: string]: any
}
// 复制商品
let setcopy = (e:any) => {
  let obj:Setcopyobj = {
    ao_id: "",
    bar_code: "",
    cost_price: "",
    g_name: "",
    gc_id: "",
    gc_name: "",
    model: "",
    sku: "",
    sku2: "",
    pic: "",
    market_price: "",
    retail_price: "",
    manufacturer: "",
    service_phone: "",
    desc: "",
    heat: 0,
    is_gift: 2,
    is_recommend: 2,
    recoverable: 1,
    performance: "",
    sell_channel: 1,
    expire_notice: 0,
    length: "",
    width: "",
    height: "",
    group_quantity: "",
    release_time: "",
    status: 1,
  };

  for (let key in obj) {
    obj[key] = e[key];
  }
  ElMessageBox.confirm($t("message.Copy"))
    .then((res) => {
      addgoods(obj).then((res) => {
        if (res.state == State.OK) {
          ElMessage({
            message: $t("message.copySuccess"),
            type: "success",
          });
          getlist();
          return;
        }
        ElMessage({
          message: $t("message.networkFailed"),
          type: "error",
        });
      });
    })
    .catch((err) => {
      console.log("取消");
    });
};
let setGtype = (row: any) => {
  if (row.g_type == 1) {
    row.g_typeCn = $t("goods.groupM.normalGood");
  }
  if (row.g_type == 2) {
    row.g_typeCn = $t("goods.groupM.hotelGood");
  }
  if (row.g_type == 3) {
    row.g_typeCn = $t("goods.groupM.ticket");
  }
  return row.g_typeCn;
};
// 导入商品信息
let setspread = () => {
  data.dialoggoods = true;
};

// 导入商品信息 - 回调
let exposegoods = (e:any) => {
  if (e) {
    getlist();
  }
  data.dialoggoods = false;
};

// 导出
let getspread = () => {
  if (data.goodsID.length == 0) {
    ElMessageBox.confirm($t("message.isExport")).then((res) => {
      exportgoodsExcel(data.goods).then((res) => {
        if (res.state == State.OK) {
          dialogExport.value = true;
          getlist();
          return;
        }
        ElMessage({
          message: $t("message.networkFailed"),
          type: "error",
        });
      });
    });
    return;
  }
  let obj = {
    g_id: data.goodsID.join(","),
  };
  ElMessageBox.confirm($t("message.isExport"))
    .then((res) => {
      exportgoodsExcel(obj)
        .then((res) => {
          if (res.state == State.OK) {
            dialogExport.value = true;
            getlist();
            return;
          }
          ElMessage({
            message: $t("message.networkFailed"),
            type: "error",
          });
        })
        .catch((err) => {
          console.log(err);
        });
    })
    .catch((err) => {
      console.log("取消");
    });
};

// 批量删除
let delspread = () => {
  if (data.goodsID.length == 0) {
    ElMessage({
      message: $t("message.pleaseSelectProduct"),
      type: "error",
    });
    return;
  }

  let id = data.goodsID.join(",");

  ElMessageBox.confirm($t("message.delData"))
    .then((res) => {
      delgoods({ g_id: id }).then((res) => {
        if (res.state == State.OK) {
          ElMessage({
            message: $t("message.delSuccess"),
            type: "success",
          });
          data.dialogVisible = false;
          getlist();
          return;
        }
        ElMessage({
          message: $t("message.networkFailed"),
          type: "error",
        });
      });
    })
    .catch((err) => {
      console.log("取消");
    });
};

// 页数回调
let current = (e:number | string) => {
  data.goods.page = e;
  getlist();
};

// 条数回调
let fraction = (e:number | string) => {
  data.goods.pageNum = e;
  getlist();
};

// 查看图片
let url = (e:string) => {
  if (e == "") {
    return;
  }
  data.title = "";
  data.gmactype = false;
  data.demonstrate = true;
  data.file_path = e;
};

gettype();
getlisttype();
</script>
